package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.poi.StringUtils;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.CodeVo;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.UserMapper;
import com.bwie.domain.User;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Override
    public R code01() {
        String code = RandomUtil.randomNumbers(4);
        redisTemplate.opsForValue().set("code-"+code,code,1, TimeUnit.MINUTES);
        return R.OK();
    }

    @Override
    public R sendCode(CodeVo codeVo) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,codeVo.getPhone());
        User one = userMapper.selectOne(wrapper);
        if(one==null) {
            return R.ERROR(404, "手机号不存在");
        }

        String code = RandomUtil.randomNumbers(4);
        redisTemplate.opsForValue().set("code-"+code,code,5, TimeUnit.MINUTES);

        String redisCode = redisTemplate.opsForValue().get("code-" + codeVo.getCode());
        if(StringUtils.isNotEmpty(redisCode)){
            return R.ERROR(404,"5分钟内只能发送一次");
        }

        MobileMessageUtil.sendMobileMessage(code,codeVo.getPhone());
        return R.OK();
    }

    @Override
    public R login(LoginVo loginVo) {
        User one = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, loginVo.getPhone()));
        if(one==null){
            return R.ERROR(404,"手机号不存在");
        }

        String redisPhoneCode = redisTemplate.opsForValue().get("code-"+loginVo.getPhoneCode());
        if(StringUtils.isEmpty(redisPhoneCode)){
            return R.ERROR(404,"验证码过期");
        }

        if(!redisPhoneCode.equals(loginVo.getPhoneCode())){
            return R.ERROR(404,"验证码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userId", one.getUserId()).compact();
        redisTemplate.opsForValue().set("token:",token,30,TimeUnit.MINUTES);
        one.setToken(token);
        return R.OK(one);
    }
}
